package com.module.organization.manager;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import base.dao.GenericHibernateDao;
import base.manager.GenericHibernateManager;
import base.util.Page;

import com.module.organization.dao.EntBindDao;
import com.module.organization.dao.OrganizationDao;
import com.module.organization.vo.EntBind;
import com.module.organization.vo.Organization;
import com.module.organization.vo.OrganizationConstant;

/**
 *
 * <服务类>
 * <企业管理类>
 *
 * @author  wurz
 * @version  [1.0, Jun 22, 2011]
 * @see  [相关类/方法]
 * @since  [二代产品/企业管理组件]
 */
public class OrganizationManager extends GenericHibernateManager<Organization, String>
{
	static Logger logger = Logger.getLogger(OrganizationManager.class.getName ()) ;
    private static OrganizationManager service;
    OrganizationDao dao = OrganizationDao.getInstance();
    EntBindDao entdao = EntBindDao.getInstance();
    public synchronized static OrganizationManager getInstance()
    {
        if (service == null)
        {
            service = new OrganizationManager();
        }
        return service;
    }
    
    private OrganizationManager(){
        
    }

    public boolean add(Organization item) throws Exception
    {
        item.setState(OrganizationConstant.NORMAL_STATE);
        return this.save(item);
    }
    /**
     * 增加企业绑定业务
     * @param bean
     * @return
     */
    public boolean saveEntBind(EntBind obj) throws Exception{
    	Session session = this.getSession();
		Transaction tx = null;
		tx = session.beginTransaction();
    	boolean result=false;
    	String enterprizeId = obj.getEnterprizeId();
    	String[] arr=obj.getCodeAppId().split(",");
    	try {
    		entdao.deleteByEnterprizeId(session,enterprizeId);
        	for(int i=0;i<arr.length;i++){
            	EntBind entBind =new EntBind();
            	entBind.setEnterprizeId(enterprizeId); 
        		entBind.setCodeAppId(arr[i]);
        		entBind.setStartTime(obj.getStartTime());
        		entBind.setEndTime(obj.getEndTime());
        		entdao.save(session,entBind);
        		result = true;
        	}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			throw e;
		} finally {
			this.closeSession();
		}
    	return result;
    }

    /**
     * 获取企业绑定的应用
     * @param entid
     * @return
     */
    
    public List getOrgApp(String entid)throws Exception{
    	Session session = this.getSession();
    	String sb = "from EntBind as obj where 1=1 and enterprizeId='"+ entid+"'";
    	try {
    		return entdao.findBySQL(session,sb);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    }
    
    /**
     * 获取登陆用户所属企业的所有子企业
     * @param id
     * @return
     */
    
    public List findOrgByPId(String id) throws Exception{
    	String sb = "from Organization as obj where id='"+ id+"' or pid='"+ id+"'";
    	return this.findBySQL(sb);
    }
    /**
     * 删除
     * @param ids
     * @return
     */
    public boolean delete(String[] ids)throws Exception
    {
        String subButter = "";
        for(int i=0;i<ids.length;i++) {
            if(i==0) {
                subButter = "id="+ids[i];
            } else {
                subButter =subButter + " or id="+ids[i];
            }
        }   

        //String hql =" delete from Organization where "+subButter;
        String hql =" update Organization set state= '"+OrganizationConstant.DELETE_STATE +"'  where "+subButter;
       
        return this.deleteByQuery(hql);
    }

    public Organization findById(String id)throws Exception
    {
        return this.get(id);
    }
    /*
    public List<Organization> findObjectListsByPage(Organization item, int firstRow, int maxRow) throws Exception
    {
        String hql =" from Organization";
        Session session = this.getSession();
		try {
			return dao.findObjectListsByPage(session,hql, firstRow, maxRow);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    }
    */
    
    public Page tolist(Organization organization,Page pageObj) throws Exception{
    	Session session = this.getSession();
		try {
			return dao.getList(session,organization,pageObj.getStart(),pageObj.getLimit());
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    }
    /**
     * 查找根结点，限定组织的这棵树必须要有个根结点
     * <功能详细描述>
     * @return
     * @see [类、类#方法、类#成员]
     */
    public List findRootNode()throws Exception{
    	Session session = this.getSession();
		try {
			return dao.findRootNode(session);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    }
    
    public List justList(Organization organization) throws Exception{
        Session session = this.getSession();
		try {
		     return dao.justList(session,organization);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    }
 
   
    public List getOrganizationTree(Organization organization)throws Exception{
        //先判断是否有根结点，如果真知码为根结点，则将次组织置为当前的根结点
    	Session session = this.getSession();
        String Pid = organization.getPid();
        Transaction tx = null;
        try {
        	List list = dao.findRootNode(session);
        if(list==null || list.size()==0){
        	Organization item = new Organization();
            item.setId("1");
            item.setPid("0");
            item.setOrganizationName("真知码");
            tx = session.beginTransaction();
            dao.save(session,item);
            tx.commit();
        }
		  return dao.getOrganizationTree(session,Pid);
		} catch (Exception e) {
			tx.rollback();
			throw e;
		} finally {
			this.closeSession();
		}
    }
    
    
    public List<Organization> getSelfTree(Organization organization) throws Exception{
    	String id =organization.getId();//eidt 2011.10.26
        Session session = this.getSession();
		try {
			return dao.getSelfTree(session,id);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    }
    
   
    public String getChildereNodeId(Organization organization) throws Exception{
        List list;
        StringBuffer str = new StringBuffer();
        Session session = this.getSession();
        try
        {
            list = dao.getSelfTree(session,organization.getId());
            //System.out.println("list.size="+list.size());
            if(!list.isEmpty()){
                Organization org = (Organization)list.get(0);
                addorgToAcc(org,str);
                String strtemp =str.toString();    
                return  strtemp.substring(0,strtemp.length()-1);
            }
        }catch (Exception e){
            throw e;
        }finally {
			this.closeSession();
		}
        return null;
    }
   
    private void addorgToAcc(Organization org,StringBuffer str)
    {
        str.append("'"+org.getId()+"',");
        List<Organization> corgList = org.getChildren();
                    
        if(corgList!=null&&corgList.size()>0)
        {
            for(int k=0;k<corgList.size();k++)
            {
                Organization orgc =corgList.get(k);
                addorgToAcc(orgc,str);
            }
        }
    }
    
    public Organization findByName(Organization organization) throws Exception{
    	String name = organization.getOrganizationName();
    	String hql = "from Organization as obj where state = '000001' and organizationName='"+ name+"'";
    	Session session = this.getSession();
		try {
			return dao.findUniqueObjectBySQL(session,hql);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    	
    }
    
    /**
     * 获取企业绑定当前可用的应用
     * @param bean
     */
    /*
    public void getOrgCurAppAndOrgName(BeanUnit bean) throws Exception{
    	Session session = this.getSession();
		try {
			List list=dao.getOrgCurApp(session,bean.getEntBind().getEnterprizeId());//getOrgCurApp(bean.getEntBind().getEnterprizeId());
			bean.setOrgEntrance(dao.getOrgEntrance(session,bean.getEntBind().getEnterprizeId()));
	    	bean.setList(list);
	    	Organization organization = dao.get(session,bean.getEntBind().getEnterprizeId());
	    	bean.setOrganization(organization);
		} catch (Exception e) {
			throw e;
		} finally {
			this.closeSession();
		}
    }
    */
    /**
     * 激活、注销企业登陆权限
     * @param bean
     * @throws Exception
     */
    /*
    public void setloginPrivilege(BeanUnit bean) throws Exception{
    	Session session = this.getSession();
    	Organization entity = bean.getOrganization();
    	String orgid = entity.getId();
    	String state = entity.getState();
    	  Transaction tx = null;
    	String hql = "update Organization set state= '"+state+"' where id='"+ orgid+"'or pid='"+ orgid+"'";
    	try{
    		 tx = session.beginTransaction();
    		 boolean isTrue =dao.deleteByQuery(session, hql);
    		 tx.commit();
    	     Map map = new HashMap();
    	     map.put("state", state);
    	     map.put("msg", "操作成功！");
    		 bean.setResult(map);
    	}catch(Exception e){
    		tx.rollback();
    		throw e;
    	}finally {
    		this.closeSession();
    	}
    }
    */
    /*
    public void getOrgNameById(BeanUnit bean) throws Exception{
    	try{
    		String orgName = dao.getOrgNameById(this.getSession(), bean.getOrganization().getId());
    		bean.setOrgName(orgName);
    	}catch (Exception e) {
			throw e;
		}finally{
			this.closeSession();
		}
    }
    */

	@Override
	public GenericHibernateDao<Organization, String> getDao() {
		return dao;
	}
 
    
}
